package com.example.userpage.controller;

import com.example.userpage.model.UserInfoDto;
import com.example.userpage.service.UserPageService;
import com.example.userpage.repository.UserMessageRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.*;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.SQLException;
import java.util.Map;

@RestController
@RequestMapping("/userpage")
@CrossOrigin(origins = "*", maxAge = 3000)
public class UserPageController {
    @Autowired
    private UserPageService userService;

    // 新增：用于读取 avatar 二进制流
    @Autowired
    private UserMessageRepository msgRepo;

    /**
     * 返回用户信息 JSON，其中 picUrl 指向 /avatar 流式接口
     */
    @PostMapping("/info")
    public UserInfoDto info(@RequestBody Map<String, String> payload,
                            HttpServletRequest request) {
        String ip = getClientIp(request);
        System.out.println("ip = " + ip);
//        String ip = payload.get("ip");
        System.out.println(ip);
        return userService.getUserInfo(ip);
    }

    /**
     * 根据客户端 IP 查询数据库 image 列，
     * 有则返回二进制流（image/png），
     * 无则返回默认静态资源 avatar.jpg（二进制流，image/jpeg）
     */
    @GetMapping("/avatar")
    public ResponseEntity<byte[]> avatar(@RequestParam("ip") String ip) throws IOException {
        // 从数据库读取 image 列
        Map<String, Object> user = msgRepo.findByIp(ip);
        Object imgObj = user.get("image");

        byte[] imageBytes = null;
        if (imgObj != null) {
            try {
                if (imgObj instanceof Blob) {
                    Blob blob = (Blob) imgObj;
                    imageBytes = blob.getBytes(1, (int) blob.length());
                } else if (imgObj instanceof byte[]) {
                    imageBytes = (byte[]) imgObj;
                }
            } catch (SQLException e) {
                throw new RuntimeException("读取用户图片失败", e);
            }
        }

        HttpHeaders headers = new HttpHeaders();
        headers.setCacheControl(CacheControl.noCache().getHeaderValue());

        if (imageBytes != null && imageBytes.length > 0) {
            // 数据库有图片，按 PNG 返回
            headers.setContentType(MediaType.IMAGE_PNG);
            return new ResponseEntity<>(imageBytes, headers, HttpStatus.OK);
        } else {
            // —— 这里改动了默认图片的路径 ——
            // 原来: new ClassPathResource("images/avatar.jpg")
            // 改为: classpath:/static/images/avatar.jpg
            ClassPathResource imgFile = new ClassPathResource("static/images/avatar.jpg");
            InputStream      in      = imgFile.getInputStream();
            byte[]           defaultBytes = StreamUtils.copyToByteArray(in);
            headers.setContentType(MediaType.IMAGE_JPEG);
            return new ResponseEntity<>(defaultBytes, headers, HttpStatus.OK);
        }
    }


    /**
     * 从请求中提取真实客户端 IP（支持代理转发头）
     */
    public static String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            // X-Forwarded-For 可能是：client, proxy1, proxy2
            // 取第一个非 unknown 的值
            String[] parts = ip.split(",");
            for (String part : parts) {
                part = part.trim();
                if (part.length() != 0 && !"unknown".equalsIgnoreCase(part)) {
                    return part;
                }
            }
        }
        ip = request.getHeader("X-Real-IP");
        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }
        // 最后退回到远端地址
        return request.getRemoteAddr();
    }
}
